package com.ow.framework.controller.action;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.ow.framework.common.Constant;
import com.ow.framework.data.handler.config.Permission;
import com.ow.framework.data.handler.config.PermissionConfig;
import com.ow.framework.data.po.PromptInfo;
import com.ow.framework.exception.DetailException;
import com.ow.framework.listener.event.EventExecutor;
import com.ow.framework.listener.event.Executor;
import com.ow.framework.proxy.Factory;
import com.ow.framework.util.DateUtil;

public abstract class BaseAction extends ActionSupport implements IAction{

	private static final long serialVersionUID = -712070397964873089L;
    /**系统权限代码，触发事件的代码*/
    private String code;
    /**进入操作页面类型，1:代表从左边菜单点击进入 0:其他无实际意义*/
    private String type;    
    /**查询参数设置对象*/
    private HashMap<String,String> searchMap = new HashMap<String,String>();    
    /**页面参数存储对象*/
    private HashMap<String,String> paramMap = new HashMap<String,String>();
	/**页面跳转前，处理初始化页面信息存储对象*/
    private HashMap<String,Object> initMap = new HashMap<String,Object>();
    /**通过配置的索引值获取任意一个权限代码对应的数值*/
    private HashMap<String,Object> pmsIndex = new HashMap<String,Object>();
    /**servlet context 对象*/
    public ActionContext ctx;
    /**servlet session 对象*/
	public Map session;
	/**事件处理器*/
	public Executor eventExecutor;
	/**页面提示信息*/
	private PromptInfo promptInfo = new PromptInfo(); 
	/**页面跳转目标文件*/
	private String directFile;
	/**当前code对应的所有直接子权限*/
	private ArrayList<Permission> subPermission;
    /**目标跳转步骤*/
    private String imitateStep;
    /**翻页默认每页页面显示记录数*/
    private String pageSize = "10";
    /**翻页时当前页数*/
    private String currentPage = "0";
    /**是否是模拟跳转*/
    private String imitateBack = "0";

	/**log 日志对象*/
	static Logger log = Logger.getLogger(Constant.FRAMEWORK);
	/**系统根目录*/
	private static String systemPath;
	
	public String execute()
	{
		try
		{
			/**获取系统根目录*/
			HttpServletRequest request = ServletActionContext.getRequest();   
			systemPath = request.getSession().getServletContext().getRealPath("/");
			if (systemPath == null)
				systemPath = request.getSession().getServletContext().getResource("/").toString();
			/**在paramMap中加入一个系统时间*/
			getParamMap().put("currentDate", DateUtil.dateToStringWithTime());
		    /**servlet context 对象*/
		    ctx = ActionContext.getContext();
		    /**servlet session 对象*/
			session = ctx.getSession();		
			/***********************************************************/
			/**只有在type等于空的情况下，根据code，获取跳页值,否者清空跳页值***/
			/***********************************************************/
			if (type == null){
				if (currentPage != null){
					try{
						//大于0说面点翻页，否者currentPage等于0
						if (Integer.parseInt(currentPage) > 0){
							session.put(code, currentPage);
						}
						else{
							if (session.get(code) != null){
								currentPage = session.get(code).toString();
							}
						}
					}
					catch(Exception e){}
				}
			}
			else{
				Iterator ite = session.keySet().iterator();
				while (ite.hasNext())
				{
					Object obj = ite.next();
					Object objValue = session.get(obj.toString());
					if (objValue instanceof String)
					{
						if (obj.toString().indexOf(code) > -1){
							session.remove(obj.toString());
						}
					}
				}				
				
			}
			
			/***********************************************************/
			/**获取session种的对象到paramMap参数对象中*/
			/***********************************************************/
			Iterator iterator = session.keySet().iterator();
			while (iterator.hasNext())
			{
				Object obj = iterator.next();
				Object objValue = session.get(obj.toString());
				if (objValue instanceof String || objValue instanceof Integer || objValue instanceof BigDecimal || objValue instanceof Short)
				{
					paramMap.put(obj.toString(), objValue.toString());
				}
			}
			/***********************************************************/
			/**获取searchMap中的所有需要检索的条件值到paramMap参数对象中*/
			/***********************************************************/
			if(!searchMap.isEmpty()){
				Iterator searchMapIter = searchMap.keySet().iterator();
				while (searchMapIter.hasNext())
				{
					Object obj = searchMapIter.next();
					Object objValue = searchMap.get(obj.toString());
					if (objValue instanceof String || objValue instanceof Integer)
					{
						paramMap.put(obj.toString(), objValue.toString());
					}
				}
			}
			try{
				/**事件执行器初始化*/
				eventExecutor = (Executor) Factory.getInstance().getInstanceProxyByParam(EventExecutor.class.getName(), new Object[]{this});
			}
			catch(Exception e){
				System.err.print(e.getMessage());			
			}
			/**执行监听事件*/
			 return subExecute();
		}
		catch (Exception e)
		{
			String error = DetailException.expDetail(e,  PermissionConfig.class);
			log.error(error);
			return ActionSupport.ERROR;
		}
	}
	
	/**
	 * 子类实现的方法
	 * @return
	 */
	public abstract String subExecute ()throws Exception;
	

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public HashMap<String,String> getSearchMap() {
		return searchMap;
	}

	public void setSearchMap(HashMap<String,String> searchMap) {
		this.searchMap = searchMap;
	}



	public HashMap<String, String> getParamMap() {
		return paramMap;
	}

	public void setParamMap(HashMap<String, String> paramMap) {
		this.paramMap = paramMap;
	}

	public HashMap<String,Object> getInitMap() {
		return initMap;
	}

	public void setInitMap(HashMap<String,Object> initMap) {
		this.initMap = initMap;
	}

	public PromptInfo getPromptInfo() {
		return promptInfo;
	}

	public void setPromptInfo(PromptInfo promptInfo) {
		this.promptInfo = promptInfo;
	}
	public String getDirectFile() {
		return directFile;
	}

	public void setDirectFile(String directFile) {
		this.directFile = directFile;
	}

	public ArrayList<Permission> getSubPermission() {
		return subPermission;
	}

	public void setSubPermission(ArrayList<Permission> subPermission) {
		this.subPermission = subPermission;
	}

	
	
	public String getImitateStep() {
		return imitateStep;
	}

	public void setImitateStep(String imitateStep) {
		this.imitateStep = imitateStep;
	}

	public String getPageSize() {
		if (pageSize.equals("0"))
			pageSize = "10";		
		return pageSize;
	}

	public void setPageSize(String pageSize) {
		this.pageSize = pageSize;
	}

	public String getCurrentPage() {
		if (currentPage.equals("0"))
			currentPage = "1";
		return currentPage;
	}

	public void setCurrentPage(String currentPage) {
		this.currentPage = currentPage;
	}

	public HashMap<String, Object> getPmsIndex() {
		return pmsIndex;
	}

	public void setPmsIndex(HashMap<String, Object> pmsIndex) {
		this.pmsIndex = pmsIndex;
	}

	public String getImitateBack() {
		return imitateBack;
	}

	public void setImitateBack(String imitateBack) {
		this.imitateBack = imitateBack;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getSystemPath() {
		return systemPath;
	}
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 获得当前应用的HttpServletResponse
	 */
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 获得当前应用的HttpSession
	 * @param isCreate:如果session不存在是否创建
	 */
	public HttpSession getSession(boolean isCreate) {
		HttpSession session = ServletActionContext.getRequest().getSession(isCreate);
		if (session == null) {
			return null;
		} else {
			return session;
		}
	}

	/**
	 * 从Request的Attribute中获取值
	 * @param key
	 * @return Object
	 */
	public Object getRequestAttr(String key) {
		return ServletActionContext.getRequest().getAttribute(key);
	}

	/**
	 * 给Request的Attribute中赋值
	 * @param key
	 * @param value
	 */
	public void setRequestAttr(String key, Object value) {
		ServletActionContext.getRequest().setAttribute(key, value);
	}

	/**
	 * 从SESSION中获得值
	 * @param key
	 * @return Object
	 */
	public Object getSessionAttr(String key) {
		HttpSession session = ServletActionContext.getRequest().getSession(false);
		if (session == null) {
			return null;
		} else {
			return session.getAttribute(key);
		}
	}

	/**
	 * 给session赋值
	 * @param key
	 * @param value
	 */
	public void setSessionAttr(String key, Object value) {
		HttpSession session = ServletActionContext.getRequest().getSession();
		session.removeAttribute(key);
		session.setAttribute(key, value);
	}

	/**
	 * 获得访问者IP
	 * @return String
	 */
	public String getRemoteIp() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return getRealIp(ip);

	}

	/**
	 * 获得去除代理的IP地址
	 * @param ip
	 * @return
	 */
	public String getRealIp(String ip) {
		String realIps[] = this.splitStr(ip, ",");
		for (int i = 0; i < realIps.length; i++) {
			if(!realIps[i].equalsIgnoreCase("unknown")){
				return realIps[i];
			}
		}
		return ip;
	}
	/**
	 * 根据传入的分割符分割数组
	 * @param str
	 * @return
	 */
	private String[] splitStr(String str, String split) {
		StringTokenizer commaToker = new StringTokenizer(str, split);
		String[] strs = new String[commaToker.countTokens()];
		int i = 0;
		while (commaToker.hasMoreTokens()) {
			strs[i] = commaToker.nextToken();
			i++;
		}
		return strs;
	}
	/**
	 * 获得访问者PORT
	 * @return int
	 */
	public int getRemotePort() {
		return ServletActionContext.getRequest().getRemotePort();
	}

	/**
	 * 获得访问者URL
	 * @return String
	 */
	public String getRequestURL() {
		StringBuilder url = new StringBuilder();
		if (null != this.getRequest().getQueryString()) {
			url.append(ServletActionContext.getRequest().getRequestURL()).append("?").append(
					this.getRequest().getQueryString());
		} else {
			url.append(ServletActionContext.getRequest().getRequestURL());
		}
		return url.toString();
	}

	/**
	 * 获得访问者浏览器
	 * @return String
	 */
	public String getRequestBrowser() {
		String userAgent = getRequestUserAgent();
		String[] agents = userAgent.split(";");
		if (agents.length > 1) {
			return agents[1].trim();
		} else {
			return null;
		}
	}

	/**
	 * 获得访问者操作系统
	 * @return String
	 */
	public String getRequestOs() {
		String userAgent = getRequestUserAgent();
		String[] agents = userAgent.split(";");
		if (agents.length > 2) {
			return agents[2].trim();
		} else {
			return null;
		}
	}

	/**
	 * 获得访问者的代理全部信息
	 * @return String
	 */
	public String getRequestUserAgent() {
		HttpServletRequest req = ServletActionContext.getRequest();
		String userAgent = req.getHeader("user-agent");
		return userAgent;
	}

	/**
	 * 添加cookie
	 * @param cookie
	 */
	public void addCookie(Cookie cookie) {
		ServletActionContext.getResponse().addCookie(cookie);
	}

	/**
	 * 获取cookie
	 * @param name
	 * @return Cookie
	 */
	public Cookie getCookie(String name) {
		Cookie[] cookies = ServletActionContext.getRequest().getCookies();
		if (cookies != null && cookies.length > 0) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals(name)) {
					return cookies[i];
				}
			}
		}
		return null;
	}

	public HashMap<String,String> getActionParamMap(){
		HashMap<String,String> resMap = new HashMap<String,String>();
		HttpServletRequest request = this.getRequest();
		Enumeration ee =request.getParameterNames();
		while(ee.hasMoreElements()){
			String name = (String)ee.nextElement();
			String value =(String)request.getParameter(name);
			resMap.put(name, value);
		}
		return resMap;
	}
	public void setSystemPath(String systemPath) {
		this.systemPath = systemPath;
	}
	
}
